package com.powernode.filter;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.powernode.constant.AuthConstants;
import com.powernode.model.LoginUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Duration;

/**
 * @description:
 * @author: mky
 * @date: 2024/7/9 10:09
 * @version: 1.0
 */
@Component
public class TokenTranslationFilter extends OncePerRequestFilter {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader(AuthConstants.AUTHORIZATION);
        if (StringUtils.hasText(token)){
            String redisKey = stringRedisTemplate.opsForValue().get(token);
            if (StringUtils.hasText(redisKey)){
                ObjectMapper objectMapper = new ObjectMapper();
                LoginUserDetails loginUserDetails = objectMapper.readValue(redisKey, LoginUserDetails.class);
//                LoginUserDetails loginUserDetails = JSON.parseObject(redisKey, LoginUserDetails.class);
                Long expire = stringRedisTemplate.getExpire(AuthConstants.TOKEN_PREFIX + token);
                if (expire<AuthConstants.TOKEN_EXPIRE_THRESHOLD_TIME){
                    stringRedisTemplate.expire(AuthConstants.TOKEN_PREFIX + token, Duration.ofSeconds(AuthConstants.TOKEN_EXPIRES_SECOND));
                }
                SecurityContext context = SecurityContextHolder.getContext();
                Authentication authentication = new UsernamePasswordAuthenticationToken(loginUserDetails,null,loginUserDetails.getAuthorities());
                context.setAuthentication(authentication);
            }
        }
        filterChain.doFilter(request,response);
    }
}
